<?php
require_once 'Database.php';
require_once 'ProductManager.php';
require_once 'CDKManager.php';

/**
 * 订单管理类
 */
class OrderManager {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * 创建订单
     */
    public function createOrder($productId, $amount, $contactInfo = '', $paymentMethod = 'easypay', $userId = 0) {
        $orderNo = $this->generateOrderNo();
        $sql = "INSERT INTO orders (order_no, product_id, total_amount, contact_info, payment_method, user_id, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())";
        
        $result = $this->db->query($sql, [$orderNo, $productId, $amount, $contactInfo, $paymentMethod, $userId]);
        
        if ($result) {
            return [
                'order_no' => $orderNo,
                'id' => $this->db->getLastInsertId()
            ];
        }
        
        return false;
    }

    /**
     * 生成订单号
     */
    private function generateOrderNo() {
        return date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    }

    /**
     * 更新订单状态
     */
    public function updateOrderStatus($orderId, $status, $paymentNo = null) {
        $sql = "UPDATE orders SET status = ?, payment_no = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->query($sql, [$status, $paymentNo, $orderId]);
    }

    /**
     * 更新订单CDK码
     */
    public function updateOrderCDK($orderId, $cdkCode) {
        $sql = "UPDATE orders SET cdk_code = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->query($sql, [$cdkCode, $orderId]);
    }

    /**
     * 根据订单号获取订单
     */
    public function getOrderByNo($orderNo) {
        $sql = "SELECT o.*, p.name as product_name, p.price as product_price, c.cdk_code
                FROM orders o 
                LEFT JOIN products p ON o.product_id = p.id 
                LEFT JOIN cdks c ON o.id = c.order_id
                WHERE o.order_no = ?";
        $result = $this->db->query($sql, [$orderNo]);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 根据ID获取订单
     */
    public function getOrderById($orderId) {
        $sql = "SELECT o.*, p.name as product_name, p.price as product_price 
                FROM orders o 
                LEFT JOIN products p ON o.product_id = p.id 
                WHERE o.id = ?";
        $result = $this->db->query($sql, [$orderId]);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 获取用户订单列表
     */
    public function getUserOrders($userId, $limit = 10, $offset = 0) {
        $sql = "SELECT o.*, p.name as product_name, p.price as product_price 
                FROM orders o 
                LEFT JOIN products p ON o.product_id = p.id 
                WHERE o.user_id = ? 
                ORDER BY o.created_at DESC 
                LIMIT ? OFFSET ?";
        return $this->db->query($sql, [$userId, $limit, $offset]);
    }

    /**
     * 获取所有订单
     */
    public function getAllOrders($status = null, $orderNo = null, $limit = 50, $offset = 0) {
        $sql = "SELECT o.*, p.name as product_name, p.price as product_price 
                FROM orders o 
                LEFT JOIN products p ON o.product_id = p.id 
                WHERE 1=1";
        
        $params = [];
        
        if ($status) {
            $sql .= " AND o.status = ?";
            $params[] = $status;
        }
        
        if ($orderNo) {
            $sql .= " AND o.order_no LIKE ?";
            $params[] = "%{$orderNo}%";
        }
        
        $sql .= " ORDER BY o.created_at DESC LIMIT ? OFFSET ?";
        $params[] = $limit;
        $params[] = $offset;
        
        return $this->db->query($sql, $params);
    }

    /**
     * 搜索订单
     */
    public function searchOrders($keyword, $limit = 50) {
        $sql = "SELECT o.*, p.name as product_name, p.price as product_price 
                FROM orders o 
                LEFT JOIN products p ON o.product_id = p.id 
                WHERE o.order_no LIKE ? OR p.name LIKE ? OR o.contact_info LIKE ?
                ORDER BY o.created_at DESC 
                LIMIT ?";
        
        $searchTerm = "%{$keyword}%";
        return $this->db->query($sql, [$searchTerm, $searchTerm, $searchTerm, $limit]);
    }

    /**
     * 获取订单统计信息（带日期范围）
     */
    public function getOrderStatisticsWithDate($startDate = null, $endDate = null) {
        $sql = "SELECT 
                COUNT(*) as total_orders,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_orders,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
                SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_orders,
                SUM(CASE WHEN status = 'completed' THEN total_amount ELSE 0 END) as total_revenue
                FROM orders";
        
        $params = [];
        if ($startDate && $endDate) {
            $sql .= " WHERE created_at BETWEEN ? AND ?";
            $params[] = $startDate;
            $params[] = $endDate;
        } elseif ($startDate) {
            $sql .= " WHERE created_at >= ?";
            $params[] = $startDate;
        } elseif ($endDate) {
            $sql .= " WHERE created_at <= ?";
            $params[] = $endDate;
        }
        
        $result = $this->db->query($sql, $params);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 删除订单
     */
    public function deleteOrder($orderId) {
        $sql = "DELETE FROM orders WHERE id = ?";
        return $this->db->query($sql, [$orderId]);
    }

    /**
     * 获取待支付订单
     */
    public function getPendingOrders($hours = 24) {
        $sql = "SELECT * FROM orders WHERE status = 'pending' AND created_at >= DATE_SUB(NOW(), INTERVAL ? HOUR)";
        return $this->db->query($sql, [$hours]);
    }

    /**
     * 获取订单统计信息
     */
    public function getOrderStatistics()
    {
        $sql = "SELECT 
                COUNT(*) as total_orders,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
                SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid_orders,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_orders,
                SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_orders,
                SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) as refunded_orders,
                SUM(total_amount) as total_amount,
                SUM(CASE WHEN status IN ('paid', 'completed') THEN total_amount ELSE 0 END) as paid_amount
                FROM orders";
        
        $result = $this->db->query($sql);
        return !empty($result) ? $result[0] : [
            'total_orders' => 0,
            'pending_orders' => 0,
            'paid_orders' => 0,
            'completed_orders' => 0,
            'failed_orders' => 0,
            'refunded_orders' => 0,
            'total_amount' => 0,
            'paid_amount' => 0
        ];
    }

    /**
     * 获取最近订单
     */
    public function getRecentOrders($limit = 10)
    {
        $sql = "SELECT o.*, p.name as product_name 
                FROM orders o 
                LEFT JOIN products p ON o.product_id = p.id 
                ORDER BY o.created_at DESC 
                LIMIT ?";
        return $this->db->query($sql, [$limit]);
    }

    /**
     * 退款订单
     */
    public function refundOrder($orderId) {
        // 开始事务
        $this->db->beginTransaction();
        
        try {
            // 获取订单信息
            $order = $this->getOrderById($orderId);
            if (!$order) {
                throw new Exception('订单不存在');
            }
            
            // 检查订单状态
            if (!in_array($order['status'], ['paid', 'completed'])) {
                throw new Exception('只有已支付或已完成的订单才能退款');
            }
            
            // 更新订单状态为已退款
            $sql = "UPDATE orders SET status = 'refunded', updated_at = NOW() WHERE id = ?";
            $this->db->query($sql, [$orderId]);
            
            // 如果订单有CDK，将其状态重置为可用
            if ($order['cdk_id']) {
                $sql = "UPDATE cdks SET status = 'available', order_id = NULL, used_at = NULL WHERE id = ?";
                $this->db->query($sql, [$order['cdk_id']]);
            }
            
            // 恢复商品库存
            $productManager = new ProductManager();
            $productManager->increaseStock($order['product_id']);
            
            // 提交事务
            $this->db->commit();
            return true;
            
        } catch (Exception $e) {
            // 回滚事务
            $this->db->rollback();
            return false;
        }
    }
}
